package com.katze.boot.common.runner;

import com.katze.boot.plugins.redis.RedisAutoConfiguration;
import com.katze.common.env.AppEnvironment;
import io.lettuce.core.RedisConnectionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

import java.net.ConnectException;

/**
 * 缓存初始化
 */
@Component
@ConditionalOnBean(RedisAutoConfiguration.class)
@ConditionalOnProperty(prefix = "spring.redis", name = "ping", havingValue = "true")
public class InitCacheRunner implements ApplicationRunner {
    private static final Logger log = LoggerFactory.getLogger(InitCacheRunner.class);
    @Autowired
    private ConfigurableApplicationContext context;

    @Override
    public void run(ApplicationArguments args) {
        try {
            log.info("Redis连接中 ······");
            context.getBean(RedisAutoConfiguration.class).ping();
        } catch (Exception e) {
            if (e instanceof ConnectException) {
                log.error("{}应用程序启动失败：{}",  AppEnvironment.APP_NAME.getValue(), e.getMessage());
            } else if (e instanceof RedisConnectionException){
                log.error("{}应用程序启动失败: Redis连接异常，请检查Redis连接配置并确保Redis服务已启动", AppEnvironment.APP_NAME.getValue(), e);
            } else {
                log.error("{}应用程序启动失败: 系统内部出现异常", AppEnvironment.APP_NAME.getValue(), e);
            }
            // 关闭程序
            context.close();
        }
    }
}
